#_*_coding:utf-8_*_
#@author:侯松林

'''
在OpenCV安装目录下找到课程对应演示图片(安装目录\sources\samples\data)，首先计算灰度直方图，进一步使用大津算法进行分割，并比较分析分割结果。
'''
import numpy as np
import cv2
from matplotlib import pyplot as plt
import time

imgs = ['pic1.png','pic2.png','pic6.png']
for j in range(3):
    # 读取图像
    imgSrc = cv2.imread(imgs[j])

    # 转化为灰度图像
    img = cv2.cvtColor(imgSrc, cv2.COLOR_BGR2GRAY)

    # global thresholding
    ret1, th1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)

    # Otsu's thresholding
    ret2, th2 = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

    # Otsu's thresholding after Gaussian filtering
    blur = cv2.GaussianBlur(img, (5, 5), 0)
    ret3, th3 = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

    # plot all the images and their histograms
    images = [img, 0, th1,
              img, 0, th2,
              blur, 0, th3]
    titles = ['Original Image', 'Histogram', 'Global Thresholding (v=127)',
              'Original Image', 'Histogram', "Otsu's Thresholding (v=" + str(ret2) + ")",
              'Gaussian filtered Image', 'Histogram', "Otsu's Thresholding (v=" + str(ret3) + ")"]

    for i in range(3):
        plt.subplot(3, 3, i * 3 + 1), plt.imshow(images[i * 3], 'gray')
        plt.title(titles[i * 3]), plt.xticks([]), plt.yticks([])
        plt.subplot(3, 3, i * 3 + 2), plt.hist(images[i * 3].ravel(), 256)
        plt.title(titles[i * 3 + 1]), plt.xticks([]), plt.yticks([])
        plt.subplot(3, 3, i * 3 + 3), plt.imshow(images[i * 3 + 2], 'gray')
        plt.title(titles[i * 3 + 2]), plt.xticks([]), plt.yticks([])
    plt.show()
    #每5秒钟切换1张图片的统计
    time.sleep(5)


'''
结论：
以上图像，对原图(pic1,pic2,pic6)应用全局阈值\大津算法\高斯滤波大津算法，可以看到
对pic1，3种处理都可以很好的分割图像；
对pic2,由于有噪声，只有第3种(高斯滤波大津算法) ,经过高斯预处理后采用大津算法，可以很好分割图像；
对pic3,3种算法都无法正确分割图像，这也是大津算法的极限性。
'''

cv2.waitKey()
cv2.destroyAllWindows()